import Vue from 'vue'
import FormDialog from './FormDialog.vue'

function getFormDialogConstructor(options, slotCmp, confirmHandler, cancelHandler) {
  return Vue.extend({
    render(h) {
      return h(FormDialog, {
        props: {
          ...options
        },
        on: {
          'confirm': async () => {
            try {
              let slotForm = this.$refs.slotChild;
              if (slotForm && slotForm.takeFormData) {
                let formData = slotForm.takeFormData();
                // 表单组件(插槽)中定义了 submitForm 方法则直接调用, 否则调用外部定义的提交表单方法
                if (slotForm.submitForm) {
                  await slotForm.submitForm(formData);
                } else if (confirmHandler) {
                  await confirmHandler(formData);
                }
              }
            } catch (error) {
              console.error('FormDialog confirm error:', error);
              // 错误时不关闭对话框，让用户可以修正
              return;
            }
            destroyDialog(this);
          },
          'cancel': () => {
            try {
              let slotForm = this.$refs.slotChild;
              if (slotForm && slotForm.clearFormData) {
                slotForm.clearFormData();
              }
              if (cancelHandler) {
                cancelHandler();
              }
            } catch (error) {
              console.error('FormDialog cancel error:', error);
            }
            destroyDialog(this);
          }
        },
        scopedSlots: {
          default: () => {
            return h(slotCmp, {
              ref: 'slotChild',
              props: {
                ...options
              }
            })
          }
        }
      })
    }
  })
}

/**
 *  销毁组件
 */
function destroyDialog(_this) {
  // 使用 Vue 的 $nextTick 确保异步操作完成后再销毁
  Vue.nextTick(() => {
    if (_this && _this.$el && _this.$el.parentNode) {
      _this.$destroy();
      _this.$el.parentNode.removeChild(_this.$el);        // 移除组件
    }
  });
}

export const useFormDialog = (options, slotCmp, confirmHandler, cancelHandler) => {
  // 确保参数有效性
  if (!slotCmp) {
    console.error('FormDialog: slotCmp is required');
    return;
  }
  
  // 合并默认选项
  const defaultOptions = {
    title: '提示',
    width: '50%',
    confirmText: '确定',
    cancelText: '取消'
  };
  
  const mergedOptions = { ...defaultOptions, ...options };
  
  const DialogConstructor = getFormDialogConstructor(
    mergedOptions,
    slotCmp,
    confirmHandler,
    cancelHandler
  );
  
  const instance = new DialogConstructor();
  instance.$mount();
  document.body.appendChild(instance.$el);
  
  // 返回实例引用，以便外部可以控制
  return instance;
}
